/**
 * 用户登录
 */

import { login } from '@/services/ant-design-pro/api';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { Alert, message, Avatar } from 'antd';
import React, { useState } from 'react';
import { history, useIntl, useModel } from 'umi';
import logo from '@/assets/images/login_logo.png';
import styles from './index.less';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const { initialState, setInitialState } = useModel('@@initialState');
  const type = 'account';

  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = await login({ ...values, type });
      if (msg.status === 'ok') {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        history.push(redirect || '/');
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultLoginFailureMessage);
    }
  };
  const { status } = userLoginState;

  return (
    <div className={styles.container}>
      <div className={styles.main}>
        <Avatar size={115} src={logo} className={styles.logo} />
        <div className={styles.title}>
          <h4>嘉图前端</h4>
        </div>
        <LoginForm
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
        >
          <div style={{ marginTop: '20px' }}>
            {status === 'error' && <LoginMessage content="账户或密码错误（admin/ant.design）" />}
            <ProFormText
              name="username"
              placeholder="账号名：admin"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              rules={[
                {
                  required: true,
                  message: '请输入登录名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              placeholder="密码：ant.design"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </div>
        </LoginForm>
      </div>
      <div className={styles.company}>copyright © 2023-江苏嘉图网络科技股份有限公司</div>
    </div>
  );
};

export default Login;
